package com.com.ruanmeng.utils;

import android.content.Context;
import android.graphics.Bitmap;

import com.alibaba.fastjson.JSON;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ToolUtils {

    public static int dp2px(Context context, int dp) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }

    public static int px2dp(Context context, int px) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (px / scale + 0.5f);
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     *
     * @param spValue （DisplayMetrics类中属性scaledDensity）
     * @return
     */
    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    public static boolean isMobileNO(String mobiles) {

        // ^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$
        Pattern p = Pattern
                .compile("^((\\d{7,8})|(0\\d{2,3}-\\d{7,8})|(1[34578]\\d{9}))$");
        Matcher m = p.matcher(mobiles);

        return m.matches();
    }


    /**
     * ���ַ�������ת��Ϊ������
     */
    public static int timeToHm(String str) {
        int time_hm = 0;
        try {
            Scanner input = new Scanner(str);//473316:47:47
            String s = input.next();
            int index1 = s.indexOf(":");
            int index2 = s.indexOf(":", index1 + 1);
            int hh = Integer.parseInt(s.substring(0, index1));//473316
            int mi = Integer.parseInt(s.substring(index1 + 1, index2));//47
            int ss = Integer.parseInt(s.substring(index2 + 1));//47
            System.out.println(hh * 3600000 + mi * 60000 + ss * 1000);
            time_hm = hh * 3600000 + mi * 60000 + ss * 1000;
            time_hm--;
        } catch (Exception e) {// 224403000
            // TODO: handle exception
        }
        return time_hm;

    }

    public static String HmToTime(long str) {
        String time = "";
        try {
            long hour = str / (60 * 60 * 1000);
            long minute = (str - hour * 60 * 60 * 1000) / (60 * 1000);
            long second = (str - hour * 60 * 60 * 1000 - minute * 60 * 1000) / 1000;
            if (second >= 60) {
                second = second % 60;
                minute += second / 60;
            }
            if (minute >= 60) {
                minute = minute % 60;
                hour += minute / 60;
            }
            String sh = "";
            String sm = "";
            String ss = "";
            if (hour < 10) {
                sh = "0" + String.valueOf(hour);
            } else {
                sh = String.valueOf(hour);
            }
            if (minute < 10) {
                sm = "0" + String.valueOf(minute);
            } else {
                sm = String.valueOf(minute);
            }
            if (second < 10) {
                ss = "0" + String.valueOf(second);
            } else {
                ss = String.valueOf(second);
            }
            System.out.println(sh + sm + ss);
            System.out.println(hour + "a" + minute + "a" + second + "a");
            time = hour + ":" + minute + ":" + second;
        } catch (Exception e) {
            // TODO: handle exception
        }
        return time;

    }

    /**
     * �����ֻ��ķֱ��ʴ� dp �ĵ�λ ת��Ϊ px(����)
     */
    public static int dip2px(Context context, double dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * ����
     *
     * @param path
     * @return
     */
    public static String bitmapToBase64(String path) {
        String result = null;
        if (!("0").equals(path)) {
            Bitmap ysbitmap = BitmapHelper.getImage(path);// ���ѹ�����bitmap
            result = Bitmap2Base64.bitmapToBase64(ysbitmap);// ��bitmap ת��base64
        } else {
            result = "0";
        }
        return result;

    }
    /**
     * ������ͼƬ�ϴ�bitapto64
     */
    /**
     * @param @param path
     * @return String ��������
     * @Description: ���ļ�תΪString����
     */
    public static String readStream(String path) {
        InputStream inStream = null;
        ByteArrayOutputStream outStream = null;
        String mImage = null;
        Bitmap afterysbitmap;
        StringBuffer buf = new StringBuffer();
        try {
            URL url = new URL(path);
            HttpURLConnection http = (HttpURLConnection) url.openConnection();
            http.setConnectTimeout(7000);
            inStream = http.getInputStream();
            byte[] buffer = new byte[1024];
            int len = -1;
            outStream = new ByteArrayOutputStream();
            try {
                while ((len = inStream.read(buffer)) != -1)
                    outStream.write(buffer, 0, len);
            } catch (IOException e) {
                e.printStackTrace();
            }
            byte[] data = outStream.toByteArray();
            /**
             * ��byte[] ת�� Bitmap
             */
            Bitmap beforeysbitmap = BitmapHelper.Bytes2Bimap(data);
            // ��ͼƬ����ѹ��
            Bitmap ysbitmap = BitmapHelper.compressImage(beforeysbitmap, 100);// ���ѹ�����bitmap
            mImage = Bitmap2Base64.bitmapToBase64(ysbitmap);// ��bitmap ת��base64
            // mImage = Base64.encodeToString(data, Base64.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outStream != null)
                try {
                    outStream.close();
                } catch (Exception e) {
                }
            if (inStream != null)
                try {
                    inStream.close();
                } catch (Exception e) {
                }
        }
        return mImage;
    }

    /**
     * 是否是邮箱
     */
    public static boolean isEmail(String strEmail) {
        // String strPattern =
        // "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        String strPattern = "^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$";

        Pattern p = Pattern.compile(strPattern);
        Matcher m = p.matcher(strEmail);
        return m.matches();
    }

    //把对象转化成Json类型的字符串
    public static String getJson(Object object) {
        HashMap<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("list", object);
        String myjson = JSON.toJSONString(hashMap);
        return myjson;
    }

    /**
     * 获取当前时间
     */
    public static String getNowTime() {
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatter.format(curDate);
        return  str;
    }
    /**
     * Android 音乐播放器应用里，读出的音乐时长为 long 类型以毫秒数为单位，例如：将 234736 转化为分钟和秒应为 03:55 （包含四舍五入）
     * @param duration 音乐时长
     * @return
     */
    public static String timeParse(long duration) {
        String time = "" ;
        long minute = duration / 60000 ;
        long seconds = duration % 60000 ;
        long second = Math.round((float)seconds/1000) ;
        if( minute < 10 ){
            time += "0" ;
        }
        time += minute+":" ;
        if( second < 10 ){
            time += "0" ;
        }
        time += second ;
        return time ;
    }

    /**
     * java 把秒转化为00:00:00格式
     * @param timeTemp
     * @return
     */
    public static String formatTime(Object timeTemp) {
        int timeParam = 0;
        if (timeTemp instanceof Integer) {
            timeParam = (Integer) timeTemp;
        }
        if (timeTemp instanceof String) {
            timeParam = Integer.valueOf((String) timeTemp);
        }

        int second = timeParam % 60;
        int minuteTemp = timeParam / 60;
        if (minuteTemp > 0) {
            int minute = minuteTemp % 60;
            int hour = minuteTemp / 60;
            if (hour > 0) {
                return (hour > 10 ? (hour + "") : ("0" + hour)) + ":" + (minute > 10 ? (minute + "") : ("0" + minute))
                        + ":" + (second >= 10 ? (second + "") : ("0" + second));
            } else {
                return "00:" + (minute > 10 ? (minute + "") : ("0" + minute)) + ":"
                        + (second >=10 ? (second + "") : ("0" + second));
            }
        } else {
            return "00:00:" + (second >= 10 ? (second + "") : ("0" + second));
        }
    }
}
